package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 点击喜欢文章用户行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        if(dto.getArticleId() == null){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser apUser = ApThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(apUser.getId() == 0){
            return ResponseResult.okResult(405,"请先登录");
        }
        //查询用户是否已经点赞
        String likes_key = "USER_LIKES_" + dto.getArticleId();
        Boolean isLike = redisTemplate.opsForHash().hasKey(likes_key, apUser.getId().toString());
        //如果已经点赞了,并且执行了点赞操作,直接返回
        if(isLike && dto.getOperation() == 0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //KafkaStream实时同步
        UpdateArticleMess articleMess = new UpdateArticleMess();
        articleMess.setArticleId(dto.getArticleId());
        articleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        //如果已经点赞了,但是执行了取消点赞操作,那就删除redis和mongodb的数据
        if(isLike && dto.getOperation() == 1){
            //删除redis
            redisTemplate.opsForHash().delete(likes_key,apUser.getId().toString());
            //删除mongodb
            mongoTemplate.remove(Query.query(Criteria.where("userId").is(apUser.getId().toString())
                    .and("articleId").is(dto.getArticleId())), ApLikesBehavior.class);

            //发送消息
            articleMess.setAdd(-1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(articleMess));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //没点赞过,进行了点赞操作,那就添加数据到redis和mongodb中
        if(!isLike && dto.getOperation() == 0){
            //添加redis
            redisTemplate.opsForHash().put(likes_key,apUser.getId().toString(),"1");
            //添加mongodb
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setId(ObjectId.get().toHexString());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setUserId(apUser.getId().longValue());
            apLikesBehavior.setType((short) 0);
            mongoTemplate.insert(apLikesBehavior);

            //发送消息
            articleMess.setAdd(1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(articleMess));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return null;
    }
}
